package com.lm56.web.waybill.controller;

import com.lm56.common.exception.FieldValidateExcetiption;
import com.lm56.common.exception.MyException;
import com.lm56.common.MyRequestBody;
import com.lm56.common.MyResponseBody;
import com.lm56.common.Utils;
import com.lm56.web.sys.domain.User;
import com.lm56.web.sys.domain.UserDetail;
import com.lm56.web.waybill.domain.Waybill;
import com.lm56.common.MyTextValuePair;
import com.lm56.web.waybill.domain.WaybillProcessForm;
import com.lm56.web.waybill.domain.WaybillQueryParams;
import com.lm56.web.waybill.domain.WaybillTraceDTO2;
import com.lm56.web.security.SecUserDetails;
import com.lm56.web.CommonService;
import com.lm56.web.sys.service.UserService;
import com.lm56.web.waybill.service.WaybillService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.validation.Valid;
import java.util.List;

/**
 * Created by Kelvin Yeung on 2016/11/27.
 */
@Controller
@RequestMapping(value = "/workbench")
public class WaybillController {

    Logger logger = LoggerFactory.getLogger(WaybillController.class);

    @Autowired
    UserService userService;

    @Autowired
    CommonService commonService;
    @Autowired
    WaybillService waybillService;


    /**
     * 运单请求分发
     */
    @PreAuthorize("hasRole('PLATFORM_USER')")
    @RequestMapping(value = "", method = RequestMethod.GET)
    public String workbench() {
        UserDetails userDetails = (UserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        User user = userService.getUserByPhoneNoOrEmail(userDetails.getUsername());
        int userType = user.getUserType();
        if (userType == User.USER_TYPE_COMPANY) {
            return "redirect:workbench/1/waybills";
        } else {
            return "redirect:workbench/2/waybills";
        }
    }


    @PreAuthorize("hasRole('USER_COMPANY')")
    @RequestMapping(value = "1/waybills", method = RequestMethod.GET)
    public String waybillsForCompany() {
        return "workbench/company/waybills";
    }


    @PreAuthorize("hasRole('USER_COMPANY')")
    @RequestMapping(value = "1/waybills", method = RequestMethod.POST)
    @ResponseBody
    public MyResponseBody waybillsForCompany(@RequestBody MyRequestBody<WaybillQueryParams> requestBody) {

        List<Waybill> waybills;
        Integer totalCount =0;
        try {
            WaybillQueryParams params = requestBody.getParams();
            if (requestBody.getQueryStr() != null) {
                if (Utils.isMobilePhoneNo(requestBody.getQueryStr())) {
                    params.setSenderPhoneNo(requestBody.getQueryStr());
                } else {
                    params.setWaybillNo(requestBody.getQueryStr());
                }
            }

            //限定查询本公司的订单
            SecUserDetails secUser = (SecUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            params.setCompanyId(secUser.getUserId());
            totalCount = waybillService.getWaybillsCountForCompany(requestBody);
            waybills = waybillService.getWaybillsForCompany(requestBody);

        } catch (Exception e) {
            e.printStackTrace();
            return new MyResponseBody(MyResponseBody.STATUS_ERROR, "获取运单数据失败");
        }
        MyResponseBody responseBody =  new MyResponseBody(MyResponseBody.STATUS_SUCESS, "获取运单数据成功", waybills);
        responseBody.setCurrentPage(requestBody.getCurrentPage());
        responseBody.setPageSize(requestBody.getPageSize());
        responseBody.setTotalSize(totalCount);
        return  responseBody;

    }

    @PreAuthorize("hasRole('USER_COMPANY')")
    @RequestMapping(value = "1/waybills/total", method = RequestMethod.POST)
    @ResponseBody
    public MyResponseBody waybillsCountForCompany(@RequestBody MyRequestBody<WaybillQueryParams> requestBody) {

        long waybillsCount;
        try {
            WaybillQueryParams params = requestBody.getParams();
            if (requestBody.getQueryStr() != null) {
                if (Utils.isMobilePhoneNo(requestBody.getQueryStr())) {
                    params.setSenderPhoneNo(requestBody.getQueryStr());
                } else {
                    params.setWaybillNo(requestBody.getQueryStr());
                }
            }
            SecUserDetails secUser = (SecUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            params.setCompanyId(secUser.getUserId());
            //companyId 必须   waybillNo 可选,senderPhoneNo 可选,waybillStatus 必须,isRecycle 必须
            waybillsCount = waybillService.getWaybillsCountForCompany(requestBody);

        } catch (Exception e) {
            return new MyResponseBody(MyResponseBody.STATUS_ERROR, "获取运单数据失败");
        }

        return new MyResponseBody(MyResponseBody.STATUS_SUCESS, "获取运单数据成功", waybillsCount);

    }


    @PreAuthorize("hasRole('USER_COMPANY')")
    @RequestMapping(value = "1/waybill/new", method = RequestMethod.GET)
    public String addWaybillForCompany(Model model) {
        //判断用户类型
        SecUserDetails secUserDetails = (SecUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Integer userType = secUserDetails.getUserType();
        //公司下订单，则把默认的公司名称、联系电话显示
        UserDetail user = userService.getUserDetailByPhoneNo(secUserDetails.getUsername());
        Waybill waybill = new Waybill();
        if (user.getContactList() != null) {
            waybill.setCompanyPhoneNo1(user.getContactList().get(0).getContactAccount());
            waybill.setCompanyPhoneNo2(user.getContactList().get(0).getContactAccount());
        }
        waybill.setCompanyId(user.getId());
        waybill.setCompanyName(user.getUserName());
        waybill.setCompanyAddr(user.getUserAddr());
        model.addAttribute("waybill", waybill);


        //获取货物单位列表
        try {
            List<MyTextValuePair<String>> unitsOfQty = commonService.getGoodsQtyUnit();
            model.addAttribute("unitsOfQty", unitsOfQty);
        } catch (RuntimeException e) {
            e.printStackTrace();
        }

        return "workbench/company/waybill_add";
    }

    @PreAuthorize("hasRole('USER_COMPANY')")
    @RequestMapping(value = "1/waybill/new", method = RequestMethod.POST)
    public String addWaybillForCompany(@Valid Waybill waybill, BindingResult result, Model model) {
        SecUserDetails secUser = (SecUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        int userType = secUser.getUserType();
        if (result.hasErrors()) {
            try {

                List<MyTextValuePair<String>> unitsOfQty = commonService.getGoodsQtyUnit();
                model.addAttribute("unitsOfQty", unitsOfQty);
            } catch (RuntimeException e) {
                e.printStackTrace();
            }

            return "workbench/company/waybill_add";

        }

        //TODO:如果是自寄的，单号必须填写？
        //TODO:公司填写的运单的类型默订是上门提货？自寄？
        try {

            waybillService.newWaybill(waybill);
        } catch (FieldValidateExcetiption e) {
            List<MyTextValuePair<String>> unitsOfQty = commonService.getGoodsQtyUnit();
            model.addAttribute("unitsOfQty", unitsOfQty);

            result.rejectValue(e.getField(), null, e.getMessage());
            return "workbench/company/waybill_add";
        }

        return "redirect:/workbench/1/waybills";

    }


    /**
     * 获取未处理的运单 页面
     *
     * @param
     * @return
     */
    @PreAuthorize("hasRole('USER_COMPANY')")
    @RequestMapping(value = "1/waybill/pending", method = RequestMethod.GET)
    public String pendingWaybillForCompany() {


        return "workbench/company/waybill_pending";
    }

    /**
     * 获取回收站的运单 页面
     *
     * @param
     * @return
     */
    @PreAuthorize("hasRole('USER_COMPANY')")
    @RequestMapping(value = "1/waybill/recycling", method = RequestMethod.GET)
    public String recyclingWaybillForCompany() {
        return "workbench/company/waybill_recycling";
    }

    @PreAuthorize("hasRole('USER_COMPANY')")
    @RequestMapping(value = "1/waybill/process", method = RequestMethod.POST)
    @ResponseBody
    public MyResponseBody processWaybilForCompany(@Valid WaybillProcessForm processForm, Model model) {


        try {
            waybillService.processWaybill(processForm);
        } catch (Exception e) {
            e.printStackTrace();
            return new MyResponseBody(MyResponseBody.STATUS_ERROR, e.getMessage());
        }

        return new MyResponseBody(MyResponseBody.STATUS_SUCESS, "处理成功");

    }


    @PreAuthorize("hasRole('USER_COMPANY')")
    @RequestMapping(value = "1/waybill/details", method = RequestMethod.GET)
    public String waybDetailsForCompany(long waybillId, String requestSrc, Model model) {
        SecUserDetails secUser = (SecUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Waybill waybill = waybillService.getWaybillDetailsForCompany(secUser.getUserId(), waybillId);
        model.addAttribute("waybill", waybill);
        model.addAttribute("requestSrc", requestSrc);
        return "workbench/company/waybill_details";
    }

    @PreAuthorize("hasRole('USER_COMPANY')")
    @RequestMapping(value = "1/waybill/details", method = RequestMethod.POST)
    public String updateWaybillDetailsForCompany(@Valid Waybill waybill, BindingResult result, HttpServletRequest request, Model model) {


        if (result.hasErrors()) {
            try {

                List<MyTextValuePair<String>> unitsOfQty = commonService.getGoodsQtyUnit();
                model.addAttribute("unitsOfQty", unitsOfQty);
            } catch (RuntimeException e) {
                e.printStackTrace();
            }
            model.addAttribute("success", "failed");
            return "workbench/company/waybill_details";
        }

        //TODO:如果是自寄的，单号必须填写？
        //TODO:公司填写的运单的类型默订是上门提货？自寄？
        try {

            waybillService.updateWaybill(waybill);
        } catch (FieldValidateExcetiption e) {
            List<MyTextValuePair<String>> unitsOfQty = commonService.getGoodsQtyUnit();
            model.addAttribute("unitsOfQty", unitsOfQty);
            result.rejectValue(e.getField(), null, e.getMessage());
            model.addAttribute("success", "failed");

            return "workbench/company/waybill_details";
        }

        //TODO:判断用户类型
        model.addAttribute("success", "success");
        String requestSrc = request.getParameter("requestSrc");
        model.addAttribute("requestSrc", requestSrc);
        return "workbench/company/waybill_details";

    }

    @PreAuthorize("hasRole('PLATFORM_USER')")
    @RequestMapping(value = "waybill/trace", method = RequestMethod.GET)
    public String waybillTrace(Long waybillId, Model model) {
        List<WaybillTraceDTO2> waybillTrace = waybillService.getWaybillTraceById(waybillId);
        model.addAttribute("waybillTrace", waybillTrace);
        return "workbench/waybill_trace";
    }

    /**
     * 把运单放进回收站
     *
     * @return
     */
    @PreAuthorize("hasRole('PLATFORM_USER')")
    @RequestMapping(value = "waybill/recycle", method = RequestMethod.POST)
    @ResponseBody
    public MyResponseBody recyleWaybill(@RequestBody MyRequestBody<List<Long>> requestBody) {

        try {
            waybillService.moveWaybillsToRecycleBin(requestBody.getParams());
        } catch (RuntimeException e) {
            e.printStackTrace();
            return new MyResponseBody(MyResponseBody.STATUS_ERROR, "运单放入回入站失败");
        }
        return new MyResponseBody(MyResponseBody.STATUS_SUCESS, "成功放入回收运单");


    }

    /**
     * 把运单从回收站还原
     *
     * @return
     */
    @PreAuthorize("hasRole('PLATFORM_USER')")
    @RequestMapping(value = "waybill/restore", method = RequestMethod.POST)
    @ResponseBody
    public MyResponseBody restoreWaybill(@RequestBody MyRequestBody<List<Long>> requestBody) {

        try {

            waybillService.restoreWaybills(requestBody.getParams());
        } catch (MyException e) {
            e.printStackTrace();
            return new MyResponseBody(MyResponseBody.STATUS_ERROR, e.getMessage());
        }
        return new MyResponseBody(MyResponseBody.STATUS_SUCESS, "成功删除运单");


    }


    /**
     * 删除运单
     *
     * @return
     */
    @PreAuthorize("hasRole('PLATFORM_USER')")
    @RequestMapping(value = "waybill/delete", method = RequestMethod.POST)
    @ResponseBody
    public MyResponseBody deleteWaybill(@RequestBody MyRequestBody<List<Long>> requestBody) {

        try {

            waybillService.deleteWaybills(requestBody.getParams());
        } catch (MyException e) {
            e.printStackTrace();
            return new MyResponseBody(MyResponseBody.STATUS_ERROR, e.getMessage());
        }
        return new MyResponseBody(MyResponseBody.STATUS_SUCESS, "成功删除运单");

    }



    /*----------------------------------------------------------------------------------------------------------------*/
    /*以下是发货人的运单处理------------------------------------------------------------------------------------------*/
    /*----------------------------------------------------------------------------------------------------------------*/


    @PreAuthorize("hasRole('USER_SENDER')")
    @RequestMapping(value = "2/waybills", method = RequestMethod.GET)
    public String waybillsForSender() {
        return "workbench/sender/waybills";
    }


    @PreAuthorize("hasRole('USER_SENDER')")
    @RequestMapping(value = "2/waybills", method = RequestMethod.POST)
    @ResponseBody
    public MyResponseBody waybillsForSender(@RequestBody MyRequestBody<WaybillQueryParams> requestBody) {

        List<Waybill> waybills;
        try {
            WaybillQueryParams params = requestBody.getParams();
            if (requestBody.getQueryStr() != null) {
                if (Utils.isMobilePhoneNo(requestBody.getQueryStr())) {
                    params.setSenderPhoneNo(requestBody.getQueryStr());
                } else {
                    params.setWaybillNo(requestBody.getQueryStr());
                }
            }

            //限定查询本公司的订单
            SecUserDetails secUser = (SecUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            params.setCompanyId(secUser.getUserId());
            waybills = waybillService.getWaybillsForSender(requestBody);

        } catch (Exception e) {
            e.printStackTrace();
            return new MyResponseBody(MyResponseBody.STATUS_ERROR, "获取运单数据失败");
        }

        return new MyResponseBody(MyResponseBody.STATUS_SUCESS, "获取运单数据成功", waybills);

    }


    @PreAuthorize("hasRole('USER_SENDER')")
    @RequestMapping(value = "2/waybill/new", method = RequestMethod.GET)
    public String addWaybillForSender(Model model) {

        //获取货物单位列表
        try {
            List<MyTextValuePair<String>> unitsOfQty = commonService.getGoodsQtyUnit();
            model.addAttribute("unitsOfQty", unitsOfQty);
        } catch (RuntimeException e) {
            e.printStackTrace();
        }

        return "workbench/sender/waybill_add";
    }

    @PreAuthorize("hasRole('USER_SENDER')")
    @RequestMapping(value = "2/waybill/new", method = RequestMethod.POST)
    public String addWaybillForSender(@Valid Waybill waybill, BindingResult result, Model model) {
        if (result.hasErrors()) {
            try {

                List<MyTextValuePair<String>> unitsOfQty = commonService.getGoodsQtyUnit();
                model.addAttribute("unitsOfQty", unitsOfQty);
            } catch (RuntimeException e) {
                e.printStackTrace();
            }

            return "workbench/sender/waybill_add";

        }

        //TODO:如果是自寄的，单号必须填写？
        //TODO:公司填写的运单的类型默订是上门提货？自寄？
        try {

            waybillService.newWaybill(waybill);
        } catch (FieldValidateExcetiption e) {
            List<MyTextValuePair<String>> unitsOfQty = commonService.getGoodsQtyUnit();
            model.addAttribute("unitsOfQty", unitsOfQty);

            result.rejectValue(e.getField(), null, e.getMessage());
            return "workbench/sender/waybill_add";
        }

        return "redirect:/sender/2/waybills";

    }


    /**
     * 获取回收站的运单 页面
     *
     * @param
     * @return
     */
    @PreAuthorize("hasRole('USER_SENDER')")
    @RequestMapping(value = "2/waybill/recycling", method = RequestMethod.GET)
    public String recyclingWaybillsForSender() {
        return "workbench/company/waybill_recycling";
    }


    @PreAuthorize("hasRole('USER_SENDER')")
    @RequestMapping(value = "2/waybill/details", method = RequestMethod.GET)
    public String waybDetailsForSender(long waybillId, String requestSrc, Model model) {
        SecUserDetails secUser = (SecUserDetails) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        Waybill waybill = waybillService.getWaybillDetailsForCompany(secUser.getUserId(), waybillId);
        model.addAttribute("waybill", waybill);
        model.addAttribute("requestSrc", requestSrc);
        return "workbench/sender/waybill_details";
    }

    @PreAuthorize("hasRole('USER_SENDER')")
    @RequestMapping(value = "2/waybill/update", method = RequestMethod.POST)
    public String updateWaybillDetailsForSender(@Valid Waybill waybill, BindingResult result, Model model) {


        if (result.hasErrors()) {
            try {

                List<MyTextValuePair<String>> unitsOfQty = commonService.getGoodsQtyUnit();
                model.addAttribute("unitsOfQty", unitsOfQty);
            } catch (RuntimeException e) {
                e.printStackTrace();
            }
            model.addAttribute("success", "failed");
            return "workbench/sender/waybill_details";
        }

        //TODO:如果是自寄的，单号必须填写？
        //TODO:公司填写的运单的类型默订是上门提货？自寄？
        try {
            waybillService.updateWaybill(waybill);
        } catch (FieldValidateExcetiption e) {
            List<MyTextValuePair<String>> unitsOfQty = commonService.getGoodsQtyUnit();
            model.addAttribute("unitsOfQty", unitsOfQty);
            result.rejectValue(e.getField(), null, e.getMessage());
            model.addAttribute("success", "failed");

            return "workbench/sender/waybill_details";
        }

        //TODO:判断用户类型
        model.addAttribute("success", "success");
        return "workbench/sender/waybill_details";

    }


}
